package com.ls.dao;

import com.sun.org.apache.bcel.internal.classfile.ClassFormatException;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author 李朔
 * @version 1.0
 */
//操作数据库的公共类
public class BaseDao {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    //静态代码块,类加载的时候就初始化了
    static {
        //通过类加载器来读取对Ying的资源
        InputStream resourceAsStream = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("user");
        password = properties.getProperty("password");

    }
        //获取数据库连接
        public static Connection getConnection() throws ClassNotFoundException {
        Connection connection=null;
            try{
                 DriverManager.registerDriver((Driver) Class.forName(driver).newInstance());
                connection = DriverManager.getConnection(url, username, password);
            }catch (Exception e){
                e.printStackTrace();
            }

            return connection;
        }
        //编写查询公共类
        public static ResultSet executeQuery(Connection connection,String sql,Object[] params,PreparedStatement preparedStatement,ResultSet resultSet) throws SQLException {
            preparedStatement=connection.prepareStatement(sql);
            for (int i = 0; i <params.length ; i++) {
                //SetObject 占位符从1开始，但是我们的数组是从0开始的
                preparedStatement.setObject(i+1,params[i]);
            }
            resultSet = preparedStatement.executeQuery();
            return resultSet;
        }

        //编写增删改公共方法
        public static int executeUpdate(Connection connection,String sql,Object[] params,PreparedStatement preparedStatement) throws SQLException {
            preparedStatement=connection.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i+1,params[i]);
            }
            int updateRows=preparedStatement.executeUpdate();
            return updateRows;
        }

        //释放资源
    public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet) throws SQLException {
        boolean flag=true;
        if(resultSet!=null){
            resultSet.close();
        }
       if(connection!=null){
           connection.close();
       }
       if(preparedStatement!=null){
            preparedStatement.close();
       }
       return flag;
    }
    }

